﻿Imports System.Xml
Public Class frmDeploy

    Dim dbConnSQL As New OleDb.OleDbConnection
    Dim sql As String
    Dim dsMain As DataSet
    Dim daMain As OleDb.OleDbDataAdapter
    Dim gAppName As String = "InventoryMan"
    Dim gTable As String = gAppName + "Info"

    Private Sub btnGetDeploy_Click(sender As System.Object, e As System.EventArgs) Handles btnGetDeploy.Click
        Dim ivManSrc As String = Application.StartupPath + "/inventoryMan/inventoryMan/bin/Release/inventoryMan.exe"
        Dim ivManTarget As String = Application.StartupPath + "/deploy/inventoryMan.exe"
        Dim ivManUpdateSrc As String = Application.StartupPath + "/updateInventoryMan/updateInventoryMan/bin/Release/updateInventoryMan.exe"
        Dim ivManUpdateTarget As String = Application.StartupPath + "/deploy/updateInventoryMan.exe"
        If gAppName = "InventoryMan" Then
            ivManSrc = Application.StartupPath + "/inventoryMan/inventoryMan/bin/Release/inventoryMan.exe"
            ivManTarget = Application.StartupPath + "/deploy/inventoryMan.exe"
            ivManUpdateSrc = Application.StartupPath + "/updateInventoryMan/updateInventoryMan/bin/Release/updateInventoryMan.exe"
            ivManUpdateTarget = Application.StartupPath + "/deploy/updateInventoryMan.exe"
        Else
            ivManSrc = Application.StartupPath + "/JDBackup/backup/bin/Debug/JDBackup.exe"
            ivManTarget = Application.StartupPath + "/deploy/JDBackup.exe"
            ivManUpdateSrc = Application.StartupPath + "/updateJDBackup/updateJDBackup/bin/Release/updateJDBackup.exe"
            ivManUpdateTarget = Application.StartupPath + "/deploy/updateJDBackup.exe"
        End If
        If System.IO.File.Exists(ivManSrc) = False Then
            MsgBox("Deploy Mode를 확인하세요.")
            Exit Sub
        End If
        Try
            My.Computer.FileSystem.CopyFile(ivManSrc, ivManTarget)
        Catch ex As Exception
            If My.Computer.FileSystem.FileExists(ivManTarget) Then
                My.Computer.FileSystem.DeleteFile(ivManTarget)
            End If
            My.Computer.FileSystem.CopyFile(ivManSrc, ivManTarget)

        End Try
        Try
            My.Computer.FileSystem.CopyFile(ivManUpdateSrc, ivManUpdateTarget)

        Catch ex As Exception

            If My.Computer.FileSystem.FileExists(ivManUpdateTarget) Then
                My.Computer.FileSystem.DeleteFile(ivManUpdateTarget)
            End If
            My.Computer.FileSystem.CopyFile(ivManUpdateSrc, ivManUpdateTarget)

        End Try
        MsgBox("배포를 위한 수집이 완료되었습니다.")
    End Sub

    Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
        Me.Dispose()
    End Sub

    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        opFileDialog.ShowDialog()
    End Sub

    Private Sub opFileDialog_FileOk(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles opFileDialog.FileOk
        txtUpdateFile.Text = opFileDialog.FileName
        txtUpdateFile.SelectionStart = txtUpdateFile.TextLength

    End Sub

    Private Sub frmDeploy_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Call dbSqlConnection()
        'Call grid1Refresh("default")
        opFileDialog.InitialDirectory = Application.StartupPath + "/deploy/"
        Call getLatestVersion()
        If My.Computer.FileSystem.FileExists(Application.StartupPath + "/config.xml") = True Then

            Dim config As XDocument = XDocument.Load(Application.StartupPath + "/config.xml")
            Dim server = From t In config.Descendants("Server") Select t.Value

            Dim user = From t In config.Descendants("User") Select t.Value

            Dim pass = From t In config.Descendants("Pass") Select t.Value

            txtUrl.Text = server.First
            txtPass.Text = pass.First
            txtUser.Text = user.First

        End If
        radio1.Checked = True
    End Sub

    Private Sub getLatestVersion()
        Dim latestVersion As String = gAFieldValue("SELECT top 1 latestVersion FROM " + gTable + " WHERE flag='Y' ORDER BY addDt DESC")
        txtVersion.Text = latestVersion
        txtVersion.Refresh()
        lbCurVersion.Text = latestVersion
        lbCurVersion.Refresh()
    End Sub

    Public Sub dbSqlConnection()
        Dim dbSrc As String
        dbSrc = "provider=sqloledb;server=inventory.jadesoft.co.kr;database=noahtech;uid=noahtech;pwd=shdkxpr7;"
        'MsgBox(dbSrc)
        dbConnSQL.ConnectionString = dbSrc
        dbConnSQL.Open()
    End Sub

    '## 쿼리를 저장하는 함수
    Public Sub gSubSaveAction(ByVal query As String, ByVal msg As String)

        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        oleCmd = New OleDb.OleDbCommand(query, dbConnSQL)

        oleTran = dbConnSQL.BeginTransaction
        oleCmd.Transaction = oleTran
        Try

            oleCmd.ExecuteNonQuery()
            oleTran.Commit()

            If msg <> "" Then
                MsgBox(msg)
            End If
            'dbConnSQL.Close()
        Catch err As OleDb.OleDbException
            oleTran.Rollback()
            dbConnSQL.Close()
            MsgBox(query)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    '## 쿼리에 대한 하나의 값 반환하기
    Private Function gAFieldValue(ByVal query As String) As String
        Dim dsCommon As DataSet
        Dim daCommon As OleDb.OleDbDataAdapter
        Dim rtnValue As String
        dsCommon = New DataSet
        daCommon = New OleDb.OleDbDataAdapter(query, dbConnSQL)
        daCommon.Fill(dsCommon, "aFieldValue")

        rtnValue = dsCommon.Tables("aFieldValue").Rows(0).Item(0)

        Return rtnValue
    End Function

    Private Sub btnDeploy_Click(sender As System.Object, e As System.EventArgs) Handles btnDeploy.Click

        Dim result As Integer = MessageBox.Show(gAppName + "을 배포 하시겠습니까?", "JDBackup", MessageBoxButtons.YesNo)
        If result = DialogResult.No Then
            Exit Sub
        ElseIf result = DialogResult.Yes Then
            Dim sql As String
            Dim fileLink As String

            Dim fileName As String
            fileName = System.IO.Path.GetFileName(opFileDialog.FileName)
            If gAppName = "InventoryMan" Then
                fileLink = "http://" + txtUrl.Text + "/inventoryMan.exe"
            Else
                fileLink = "http://" + txtUrl.Text + "/JDBackup.exe"
            End If
            If txtUrl.Text = "" Then
                MsgBox("URL을 바르게 입력해 주세요")
                txtUrl.Focus()
                Exit Sub
            End If
            If txtVersion.Text = "" Then
                MsgBox("버전을 바르게 입력해 주세요")
                txtVersion.Focus()
                Exit Sub
            End If
            If txtVersion.Text = lbCurVersion.Text Then
                MsgBox("이전 버전 정보와 동일한 버전은 입력할 수 없습니다.")
                txtVersion.Focus()
                Exit Sub
            End If
            ProgressBar.Value = 5
            txtLog.Text += "============== 인벤토리맨 배포 시작 ==============" + vbCrLf
            txtLog.Refresh()
            txtLog.Focus()
            txtLog.SelectionStart = txtLog.TextLength
            txtLog.ScrollToCaret()
            sql = "INSERT INTO " + gTable + " (latestVersion, fileLink, updateMsg, flag) VALUES('" + txtVersion.Text + "', '" + fileLink + "','" + txtMessage.Text + "','Y')"
            Call mkConfig()
            Call ftpUpload(fileName)

            Dim curDt As DateTime = Now
            txtLog.Text += "[" + curDt.ToString + "] 배포 완료......Ok" + vbCrLf + "------------------------------------------------" + vbCrLf + vbCrLf
            txtLog.Refresh()
            txtLog.Focus()
            txtLog.SelectionStart = txtLog.TextLength
            txtLog.ScrollToCaret()
            ProgressBar.Value += 30
            gSubSaveAction(sql, "배포가 완료 되었습니다.")
            Call getLatestVersion()
        End If
    End Sub

    Private Sub ftpUpload(fileName)
        Dim rq As System.Net.FtpWebRequest
        Dim ftpUrl As String

        ftpUrl = "ftp://" + txtUrl.Text + "/" + fileName
        rq = DirectCast(System.Net.WebRequest.Create(ftpUrl), System.Net.FtpWebRequest)
        rq.Credentials = New System.Net.NetworkCredential(txtUser.Text, txtPass.Text)
        rq.Method = System.Net.WebRequestMethods.Ftp.UploadFile

        Dim files() As Byte = System.IO.File.ReadAllBytes(txtUpdateFile.Text)

        Dim strz As System.IO.Stream = rq.GetRequestStream()
        strz.Write(files, 0, files.Length)
        strz.Close()
        strz.Dispose()
        Dim curDt As DateTime = Now
        txtLog.Text += "[" + curDt.ToString + "] 파일 업로드 완료......Ok" + vbCrLf
        txtLog.Refresh()
        txtLog.Focus()
        txtLog.SelectionStart = txtLog.TextLength
        txtLog.ScrollToCaret()
        ProgressBar.Value += 50
        Threading.Thread.Sleep(500)
    End Sub

    Private Sub createNode(ByVal serverUrl As String, ByVal uid As String, ByVal pass As String, ByVal writer As XmlTextWriter)
        writer.WriteStartElement("Server")
        writer.WriteString(serverUrl)
        writer.WriteEndElement()
        writer.WriteStartElement("User")
        writer.WriteString(uid)
        writer.WriteEndElement()
        writer.WriteStartElement("Pass")
        writer.WriteString(pass)
        writer.WriteEndElement()
    End Sub

    Private Sub mkConfig()
        Dim writer As New XmlTextWriter("config.xml", System.Text.Encoding.UTF8)
        writer.WriteStartDocument(True)
        writer.Formatting = Formatting.Indented
        writer.Indentation = 2
        writer.WriteStartElement("DeployConfig")
        createNode(txtUrl.Text, txtUser.Text, txtPass.Text, writer)
        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Close()
        Dim curDt As DateTime = Now
        txtLog.Text += "[" + curDt.ToString + "] 로그 파일 저장......Ok" + vbCrLf
        txtLog.Refresh()
        txtLog.Focus()
        txtLog.SelectionStart = txtLog.TextLength
        txtLog.ScrollToCaret()
        Threading.Thread.Sleep(500)
        ProgressBar.Value += 15
    End Sub

    'Private Sub txtVersion_LostFocus(sender As System.Object, e As System.EventArgs) Handles txtVersion.LostFocus

    '    txtMessage.Text = "----- Ver " + txtVersion.Text + " 업데이트 내용 -----" + vbCrLf + vbCrLf
    '    txtMessage.Text += " - " + vbCrLf + vbCrLf
    '    txtMessage.Text += "---------------------------------" + vbCrLf
    '    txtMessage.Refresh()
    'End Sub

    Private Sub grid1Refresh(ByVal initFlag As String)
        Dim addSql As String = ""

        dsMain = New DataSet
        If initFlag = "default" Then
            addSql = " WHERE loginId=''"
        End If
        sql = "SELECT top 100  seq, loginId 아이디, version 내용, ip 맥어디르레스, wDate 일자 " & _
            "   FROM InventoryManLog " + addSql + " ORDER BY wDate DESC"

        Try
            daMain = New OleDb.OleDbDataAdapter(sql, dbConnSQL)
            daMain.Fill(dsMain, "loginLOG")

            grdLog.DataSource = dsMain.Tables("loginLOG")

            'dbConnSQL.Close()
            Call setGrid1Design()

        Catch err As ObjectDisposedException
            dbConnSQL.Close()
            MsgBox(sql)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    Private Sub setGrid1Design()

        grdLog.Columns(0).Visible = False
        grdLog.Columns(1).Width = "150"
        grdLog.Columns(2).Width = "100"
        grdLog.Columns(3).Width = "140"
        grdLog.Columns(4).Width = "130"
        grdLog.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft

        With grdLog.DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleCenter
        End With

    End Sub


    'Private Sub grid2Refresh(ByVal initFlag As String)
    '    Dim addSql As String = ""

    '    dsMain = New DataSet
    '    If initFlag = "default" Then
    '        addSql = " WHERE loingId=''"
    '    End If
    '    sql = "SELECT top 100  seq, userId 아이디, userEmail E-mail, userNm 이름, wDate 일자 " & _
    '        "   FROM InventoryManAuth " + addSql + " ORDER BY wDate DESC"

    '    Try
    '        daMain = New OleDb.OleDbDataAdapter(sql, dbConnSQL)
    '        daMain.Fill(dsMain, "loginLOG")

    '        grdLog.DataSource = dsMain.Tables("loginLOG")

    '        'dbConnSQL.Close()
    '        Call setGrid1Design()

    '    Catch err As ObjectDisposedException
    '        dbConnSQL.Close()
    '        MsgBox(sql)

    '        MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
    '    End Try
    'End Sub

    'Private Sub setGrid2Design()

    '    grdLog.Columns(0).Visible = False
    '    grdLog.Columns(1).Width = "150"
    '    grdLog.Columns(2).Width = "100"
    '    grdLog.Columns(3).Width = "140"
    '    grdLog.Columns(4).Width = "130"
    '    grdLog.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft

    '    With grdLog.DefaultCellStyle
    '        .Alignment = DataGridViewContentAlignment.MiddleCenter
    '    End With

    'End Sub

    Private Sub btnSearchLog_Click(sender As System.Object, e As System.EventArgs) Handles btnSearchLog.Click
        Call grid1Refresh("")
    End Sub

    Private Sub btnUpload_Click(sender As System.Object, e As System.EventArgs) Handles btnUpload.Click

        Dim fileName As String
        fileName = System.IO.Path.GetFileName(opFileDialog.FileName)
        Call ftpUpload(fileName)
        ProgressBar.Value = 0
    End Sub

    Private Sub radio1_Click(sender As Object, e As System.EventArgs) Handles radio1.Click
        If radio1.Checked = True Then
            opFileDialog.FileName = "inventoryMan.exe"
            gAppName = "InventoryMan"
            gTable = gAppName + "Info"
            Call getLatestVersion()
        End If

    End Sub

    Private Sub radio2_Click(sender As Object, e As System.EventArgs) Handles radio2.Click
        If radio2.Checked = True Then
            opFileDialog.FileName = "JDBackup.exe"
            gAppName = "JDBackup"
            gTable = gAppName + "Info"
            Call getLatestVersion()
        End If

    End Sub
End Class
